package 我的Java学习_算法基础.day_05;

public class _087_尺取法例题 {
    public static void main(String[] args) {
        String s = "hieho";
        solve(s);
    }
    //hiho字符串
    private static void solve(String s){
        char[] w = s.toCharArray();
        int min = Integer.MAX_VALUE;
        int j = -1;
        for(int i =0;i<w.length;i++){
            char c = w[i];
            if(check(c)){
                if(j==-1){//j的第一次定位
                    j=i+1;
                }
                while(j<w.length) {
                    char c2 = w[j];
                    if (check(c2) && containsAll(w, i, j)) {//全部囊括
                        if (check(w, i, j) && j - i + 1 < min) {//更新min
                            min = j - i + 1;
                        }
                        break;//停下
                    }
                    j++;//j继续扫描
                }
            }

        }
        System.out.println(min==Integer.MAX_VALUE?-1:min);
    }

    /**
     * 恰好包含2个h，1个i,1个o
     * @param w
     * @param i
     * @param j
     * @return
     */
    private static boolean check(char[] w,int i,int j){
        int c1 = 0,c2 = 0,c3 = 0;
        for(int k =i;k<=j;k++){
            if(w[k]=='h') c1++;
            if(w[k]=='i') c2++;
            if(w[k]=='o') c3++;
        }
        return c1==2&&c2==1&&c3==1;
    }

    /**
     * 该字符是否是h.i.o中的一个
     * @param c
     * @return
     */
    private static boolean check(char c){
        return c == 'h'||c == 'i'||c == 'o';
    }

    /**
     * i--j至少包含了1个hiho
     * @param w
     * @param i
     * @param j
     * @return
     */
    private static boolean containsAll(char[] w,int i,int j){
        int c1 = 0,c2=0,c3=0;
        for(int k =i;k<=j;k++){
            if(w[k]=='h') c1++;
            if(w[k]=='i') c2++;
            if(w[k]=='o') c3++;
        }
        return c1>=2&&c2>=1&&c3>=1;
    }

}
